import { ref, onUnmounted } from 'vue';

type CountdownReturn = {
  countdown: number;
  isCounting: boolean;
  startCountdown: () => void;
};

export function useCountdown(duration: number): CountdownReturn {
  const countdown = ref<number>(duration);
  const isCounting = ref<boolean>(false);
  let intervalId: ReturnType<typeof setInterval> | null = null;

  const startCountdown = (): void => {
    if (!isCounting.value) {
      isCounting.value = true;
      intervalId = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
          clearInterval(intervalId!);
          isCounting.value = false;
          countdown.value = duration;
        }
      }, 1000);
    }
  };

  onUnmounted(() => {
    if (intervalId) {
      clearInterval(intervalId);
    }
  });

  return {
    countdown: countdown.value,
    isCounting: isCounting.value,
    startCountdown
  };
}
